﻿using System;
using System.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceProcess;
using System.Timers;

namespace BarManager.Printer.Ticket
{
    partial class PrintService : ServiceBase
    {
        private ServiceHost host;
        private Timer timer;

        public PrintService()
        {
            InitializeComponent();

            timer = new Timer(500);
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Stop();
        }

        private void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            timer.Stop();
            try
            {
                if (host != null) host.Close();
                host = new ServiceHost(typeof(WCF.Process));
                host.Open();
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(ex.Source, ex.Message, EventLogEntryType.Error);
                if (host.State == CommunicationState.Faulted) host.Close();
                timer.Start();
            }
        }

        protected override void OnStart(string[] args)
        {
            EventLog.WriteEntry("Inicia el servicio BarManager.Printer.Ticket", EventLogEntryType.Information);
            timer.Start();
        }

        protected override void OnStop()
        {
            EventLog.WriteEntry("Se detiene el servicio BarManager.Printer.Ticket", EventLogEntryType.Information);
            if (host != null) host.Close();
            host = null;
            timer = null;
        }
    }
}
